<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Htlogin
    extends CI_Controller
    {
    public $error;

    function __construct() { parent::__construct();
    //$this->load->library('PHT');
    }

    function index()
        {
        $this->load->library('session');
        $data=$this->session->userdata('HTdata');

        if ($data)
            $HT=$data[0];
        else
            $HT=false;

        unset($data);

        if ($HT)
            {
            if (isset($_REQUEST['oauth_token']) && isset($_REQUEST['oauth_verifier']))
                {
                $HT->retrieveAccessToken($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']);
                }
            /*
            Now access is granted for your application
            You can save user token and token secret and/or request xml files
            */
            $userToken      =$HT->getOauthToken();
            $userTokenSecret=$HT->getOauthTokenSecret();

            /*
            * Здесь нужно написать алгоритм проверки юзера в базе и создания его класса и соответсвующих прав
            * 
            */
            $userID         =$HT->getTeam()->getUserId();

            if (!$userID)
                {
                $this->_clear_data();
                return false;
                }

            $nick           =$userName=$HT->getTeam()->getLoginName();

            $query_str      ="
                    SELECT u.* FROM
                    " . $this->db->dbprefix . "users u
                    WHERE
                    u.userID = %s  LIMIT 1";
            //$userTokenSecret=(md5($passw)); // должно быть вот так, если в базе хранятся md5-хэши паролей! 
             

            $query_params=array
                (
                $this->db->escape($userID),
                $this->db->escape($nick),
                $this->db->escape($userTokenSecret),
                $this->db->escape($userToken)
                );

            $result=$this->db->query(vsprintf($query_str, $query_params));

            if ($result)
                $user=$result->row_array();

            if (!$user)
                {
                if ($HT->getTeam()->getLeagueId() == 68)
                    $class=3;
                else
                    $class=2;

                $query_str
                       ="INSERT INTO " . $this->db->dbprefix . "users
                      (`userID`, `class_id`, `userName`, `loginName`, `securityCode`, `UsecCode`) VALUES (%s, '" . $class . "', %s, " . $this->db->escape($userName)
                    . ", %s, %s)";
                $result=$this->db->query(vsprintf($query_str, $query_params));
                }
            else
                {
                if (!$user['class_id'])
                    if ($HT->getTeam()->getLeagueId() == 68)
                        $user['class_id']=3;
                    else
                        $user['class_id']=2;

                $query_str
                             ="UPDATE " . $this->CI->db->dbprefix . "users
                      SET `UsecCode`= %s,  `securityCode`= %s, `userName`=" . $this->db->escape(
                                                                                  $nick) . ", `class_id`='" . $user['class_id'] . "', `loginName`=" . $this->db->escape($userName) . "
                      WHERE `userID`= %s
                      ";
                $query_params='';

                $query_params=array
                    (
                    $this->db->escape($userToken),
                    $this->db->escape($userTokenSecret),
                    $this->db->escape($userID)
                    );

                $str   =vsprintf($query_str, $query_params);
                $result=$this->db->query(vsprintf($query_str, $query_params));
                }


            /*********************************/

            $usrdata = array('usrTok'=>$userToken,    'usrTokSec'=>$userTokenSecret, 'usrId'=>$userID);
            $this->session->set_userdata($usrdata);
            
            $this->load->helper('cookie');
            $expire=2678400;  $domain=$this->config->item('cookie_domain'); $path=$this->config->item('cookie_path'); $prefix =$this->config->item('cookie_prefix');
            set_cookie('usrTok', $userToken, $expire, $domain, $path, $prefix);
            set_cookie('usrTokSec', $userTokenSecret, $expire, $domain, $path, $prefix);
            set_cookie('usrId', $userID, $expire, $domain, $path, $prefix);
            
            
            
            }
     redirect('', 'refresh'); //перенаправляем на главную страничку
        }
        
    function connectToHT()
    {
            //if ($this->input->post('Send')) //если данных нет в сессии, то проверяем, нажата ли кнопка авторизации
            {
            $this->load->config('CHPP');

            $HT =new CHPPConnection($this->config->item('consumerKey'), $this->config->item('consumerSecret'),
                                    $this->config->item('callbackUrl'));

            $url=$HT->getAuthorizeUrl();
            $this->session->set_userdata('HTdata', array($HT));

            redirect($url, 'refresh');
            exit;
            }
    }
    
    
    function logout()
    {
        $this->_clear_data();
        redirect ('', 'refresh');
        
    }
    function _clear_data()
    {
                $this->session->sess_destroy();
                $domain=$this->config->item('cookie_domain'); $path=$this->config->item('cookie_path'); $prefix =$this->config->item('cookie_prefix');
                delete_cookie('usrTok', $domain, $path, $prefix);
                delete_cookie('usrTokSec', $domain, $path, $prefix);
                delete_cookie('usrId', $domain, $path, $prefix);
    }    
        
    }
?>